package com.swsc.ai.common;

import com.swsc.ai.enums.CommonResultCode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.function.Supplier;

/**
 * @describe: 统一接口返回通用类
 * @author: 容若
 * @created: 2024-06-20 13:04
 */
@Data
@Slf4j
public class Result<T> implements Serializable {
    private String code;
    private String msg;
    private T data;
    private Boolean success;

    public boolean isSuccess() {
        return CommonResultCode.SUCCESS.getCode().equals(this.code);
    }

    private Result() {
    }

    private Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.success = CommonResultCode.SUCCESS.getCode().equals(this.code);
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        return result(CommonResultCode.SUCCESS, data);
    }

    public static <T> Result<T> success(String msg, T data) {
        return result(CommonResultCode.SUCCESS, msg, data);
    }

    public static <T> Result<T> error() {
        return error(null);
    }

    public static <T> Result<T> error(T data) {
        return result(CommonResultCode.ERROR, data);
    }

    public static <T> Result<T> error(String msg, T data) {
        return result(CommonResultCode.ERROR, msg, data);
    }


    public static <T> Result<T> result(CommonResultCode commonResultCode, T data) {
        return new <T>Result(commonResultCode.getCode(), commonResultCode.getMsg(), data);
    }

    public static <T> Result<T> result(CommonResultCode commonResultCode, String msg, T data) {
        return new <T>Result(commonResultCode.getCode(), msg, data);
    }

    public static <T> Result<T> result(Supplier<T> supplier) {
        T apply = supplier.get();
        if (apply instanceof Throwable) {
            return error(apply);
        } else {
            return success(apply);
        }
    }
}
